package com.ruoyi.system.api;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.easemob.im.server.model.EMUser;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisUtil;
import com.ruoyi.common.huanxing.EMServiceUtil;
import com.ruoyi.common.utils.CommonUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.security.auth.JWTUser;
import com.ruoyi.framework.security.auth.RequestContext;
import com.ruoyi.system.domain.PriceSetting;
import com.ruoyi.system.domain.Report;
import com.ruoyi.system.domain.UserFeedback;
import com.ruoyi.system.mapper.PriceSettingMapper;
import com.ruoyi.system.pojo.AppSystemMsgDTO;
import com.ruoyi.system.pojo.AppTaskRewardDTO;
import com.ruoyi.system.service.AppSystemService;
import com.ruoyi.thread.TaskAsync;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.domain.UserExtend;
import com.ruoyi.user.mapper.UserExtendMapper;
import com.ruoyi.user.pojo.AppAccountManageVO;
import com.ruoyi.user.pojo.AppRegister;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import io.swagger.annotations.Api;

@RestController
@RequestMapping("/api/v1/system")
@Api(tags = "【APP】系统参数相关接口")
@CrossOrigin
public class AppSystemController {

	@Autowired
	private AppSystemService appSystemService;
	@Autowired
	private PriceSettingMapper priceSettingMapper;
	@Autowired
	private EMServiceUtil eMServiceUtil;
	@Autowired
	private UserExtendMapper userExtendMapper;
	
	@GetMapping(value = "/emTest")
	public AjaxResult emTest(String userName) {
		List<UserExtend> list = userExtendMapper.selectList(null);
		list.stream().forEach(u ->{
			String nickName = CommonUtil.getRandomUserName();
			EMUser createUser = eMServiceUtil.createUser(nickName);
			u.setEmUsername(createUser.getUsername());
			u.setEmPassword(createUser.getUsername());
			u.setUpdateTime(new Date());
			userExtendMapper.updateById(u);
		});
		
		return AjaxResult.success();
	}
	
	@PostMapping(value = "/dateTest")
	public AjaxResult dateTest(@RequestBody User user) {
		
		System.out.println(user);
		return AjaxResult.success();
	}
	
	
	
	/**
	 * 	获取会员权益描述
	 * @return
	 */
	@GetMapping(value = "/getVipRemark")
	public AjaxResult getVipRemark() {
		PriceSetting set = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>()
				.eq(PriceSetting::getPriceType, "vipRemark").select(PriceSetting::getId,PriceSetting::getPriceName).last("limit 1"));
		String str = "暂无";
		if(null != set && StringUtils.isNotEmpty(set.getPriceName())) {
			str = set.getPriceName();
		}
		return AjaxResult.success("成功",str);
	}
	
	@GetMapping(value = "/getVipServerRemark")
	public AjaxResult getVipServerRemark() {
		PriceSetting set = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>()
				.eq(PriceSetting::getPriceType, "vipServerRemark").select(PriceSetting::getId,PriceSetting::getPriceName).last("limit 1"));
		String str = "暂无";
		if(null != set && StringUtils.isNotEmpty(set.getPriceName())) {
			str = set.getPriceName();
		}
		return AjaxResult.success("成功",str);
	}
	
	
	/**
	 * 	token失效记录
	 * @param phone
	 * @return
	 */
	@GetMapping(value = "/recordErrorLog")
	public AjaxResult recordErrorLog(String phone) {
		redisUtil.set("recordErrorLog_"+phone, DateUtil.now());
		return AjaxResult.success();
	}
	
	
	/**
	 * 	密码失效记录日志
	 * @param data
	 * @return
	 */
	@PostMapping(value = "/invalidPwdLog")
	public AjaxResult invalidPwdLog(@RequestBody String data) {
		Long userId = 0L;
		Object object = RequestContext.get("userInfo");
		if(null != object) {
			JWTUser jwtUser = (JWTUser) object;
			if(null != jwtUser && null != jwtUser.getId()) {
				userId = jwtUser.getId();
			}
		}
		redisUtil.set("invalidPwdLog_"+userId+"_"+ DateUtil.now(), data);
		return AjaxResult.success();
	}
	
	

	/**
	 * 	获取用户聊天记录
	 * @param multipartFile
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@PostMapping(value = "/fileUploadUrl")
	public AjaxResult fileUploadUrl(MultipartFile multipartFile){
		try {
			//取一个随机id给文件重命名使用
			String uuid = UUID.randomUUID().toString();
			//你的接收的文件新的名字
			String filename = uuid;
			//在项目新建一个 你重新生成名称的文件
			//File file = new File("F:\\gz\\"+filename);
			File file = new File("/www/wwwroot/file/"+filename);
			//将接收的到的 multipartFile 类型的文件 转为 file
			multipartFile.transferTo(file);
			//获取接收到的并存在项目本地的文件，这样你就可以拿着这个文件随意处理啦
			String filePath = file.getAbsolutePath();
			System.out.println(filePath);
			List<ChatRecordDTO> fileOfHutool = GZFileExtractor.fileOfHutool(filePath);
			file.delete();
			return AjaxResult.success(fileOfHutool);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error(e.getMessage());
		}
	}

	@GetMapping(value = "/test")
	public AjaxResult test(String date) throws ClientProtocolException, IOException {
//		String historyAsUri = eMServiceUtil.getHistoryAsUri();
//		System.out.println("返回数据：");
//		System.out.println(historyAsUri);
//		return AjaxResult.success(JSONObject.toJSONString(historyAsUri));
		String url = "https://a1.easemob.com/1151230809175214/demo/chatmessages/"+date;
		RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
		HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
		HttpGet httpget = new HttpGet(url);
		httpget.addHeader("Accept","application/json");
		httpget.addHeader("Authorization","Bearer YWMt-1ausHJLEe6C0eeaOhqstpPaTfaxrjFvim9cX9VmPio9qcpjmD1G-ax5qJAbq82LAgMAAAGLYOtPmTeeSAABld7sAiUix_s27elX8l4LqVyT7yRIbZLVTWffVBs_uQ");
		HttpResponse execute = httpClient.execute(httpget);
		String string = EntityUtils.toString(execute.getEntity(),"UTF-8");
		System.out.println(string);
		return AjaxResult.success(string);
	}

	/**
	 * 	发送短信验证码
	 * @param mobile	手机号码
	 * @param type		1=注册/登录 2=绑定手机 3=修改手机号码 4=注销验证手机号码 5=邀请绑定手机号码 6=添加绑定账号7=重置密码
	 * @return
	 */
	@GetMapping(value = "/sendCode")
	public AjaxResult sendCode(String mobile, Integer type) {
		if (StringUtils.isEmpty(mobile)) {
			return AjaxResult.error("检测到手机号码有误，请重新输入");
		}
		return appSystemService.sendMobileCode(mobile, type);
	}

	/**
	 * 	获取用户使用意图list
	 * @return
	 */
	@GetMapping(value = "/qryUserPurposeList")
	public AjaxResult qryUserPurposeList() {
		return appSystemService.qryUserPurposeList();
	}

	/**
	 * 	平台内定参数获取
	 * @param type		1=充值余额 2=充值VIP 3=提现比例 4=动态banner 5=礼物列表 6=约玩类型列表 7=话题列表 8=消息banner
	 * @param parentId	上级id 用于type=5时
	 * @return
	 */
	@GetMapping(value = "/getParameterList")
	public AjaxResult parameterList(Integer type,Integer parentId,HttpServletRequest request) {
		if(null == parentId) {
			parentId = 0;
		}
		return appSystemService.parameterList(type,parentId,request);
	}

	/**
	 * 	获取用户任务奖励列表
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/getUserTaskRewardList")
	public AjaxResult getUserTaskRewardList(HttpServletRequest request) {
		return appSystemService.getUserTaskRewardList(request);
	}

	/**
	 * 	获取隐私设置
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/getPrivacySet")
	public AjaxResult getPrivacySet(HttpServletRequest request) {
		return appSystemService.getPrivacySet(request);
	}

	/**
	 * 	修改隐私设置
	 * @param type		1=距离展示 2=隐身访问
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/updatePrivacySet")
	public AjaxResult updatePrivacySet(@RequestBody AppTaskRewardDTO type,HttpServletRequest request) {
		if(null == type) {
			type = new AppTaskRewardDTO();
			type.setType(0);
		}
		if(null == type.getType()) {
			type.setType(0);
		}
		return appSystemService.updatePrivacySet(type.getType(),request);
	}


	/**
	 * 	获取通知设置
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/getNoticeSet")
	public AjaxResult getNoticeSet(HttpServletRequest request) {
		return appSystemService.getNoticeSet(request);
	}

	/**
	 * 	修改通知设置
	 * @param type		1=关注上线通知 2=关注用户发布动态 3=新增粉丝 4=TA看过我 5=互动奖励 6=邀请好友
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/updateNoticeSet")
	public AjaxResult updateNoticeSet(@RequestBody AppTaskRewardDTO type,HttpServletRequest request) {
		if(null == type) {
			type = new AppTaskRewardDTO();
			type.setType(0);
		}
		if(null == type.getType()) {
			type.setType(0);
		}
		return appSystemService.updateNoticeSet(type.getType(),request);
	}

	/**
	 * 	修改绑定手机号码
	 * @param appRegister
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/updatePhone")
	public AjaxResult updatePhone(@RequestBody AppRegister appRegister,HttpServletRequest request) {
		if(null == appRegister || StringUtils.isEmpty(appRegister.getMobile())) {
			return AjaxResult.error("请输入新手机号码");
		}
		if(StringUtils.isEmpty(appRegister.getMobileCode())) {
			return AjaxResult.error("请输入验证码");
		}
		return appSystemService.updatePhone(appRegister.getMobile(),appRegister.getMobileCode(),request);
	}

	/**
	 * 	提交意见反馈
	 * @param userFeedback
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/submitFeedback")
	public AjaxResult submitFeedback(@RequestBody UserFeedback userFeedback,HttpServletRequest request) {
		if(null == userFeedback || StringUtils.isEmpty(userFeedback.getContent())) {
			return AjaxResult.error("请输入反馈内容");
		}
		if(StringUtils.isEmpty(userFeedback.getContact())) {
			return AjaxResult.error("请输入联系方式");	
		}
		return appSystemService.submitFeedback(userFeedback,request);
	}

	/**
	 * 	帮助中心
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/getHelpCenter")
	public AjaxResult getHelpCenter(HttpServletRequest request) {
		return appSystemService.getHelpCenter(request);
	}

	/**
	 * 	设置消息通知
	 * @param type		1=消息通知 2=抢单池通知
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/setMsgNotice")
	public AjaxResult setMsgNotice(@RequestBody AppSystemMsgDTO msg,HttpServletRequest request) {
		if(null == msg || null == msg.getType()) {
			return AjaxResult.error("请选择消息类型");
		}
		return appSystemService.setMsgNotice(msg.getType(),request);
	}

	/**
	 * 	获取举报设置
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/getReportSetting")
	public AjaxResult getReportSetting(HttpServletRequest request) {
		return appSystemService.getReportSetting(request);
	}

	/**
	 * 	举报用户
	 * @param report
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/reportUser")
	public AjaxResult reportUser(@RequestBody Report report,HttpServletRequest request) {
		if(null == report) {AjaxResult.error("请选择举报类型");}
		if(StringUtils.isEmpty(report.getReasonCode())) {AjaxResult.error("请选择举报类型");}
		if(null == report.getReportedUserId()) {AjaxResult.error("请选择举报用户");}
		return appSystemService.reportUser(report,request);
	}

	/**
	 * 	获取占卜真实案例
	 * @param type	 类型 1=卡牌问答 2=骰子问答 3=星盘问答 4=六爻
	 * @return
	 */
	@GetMapping(value = "/getDivineCase")
	public AjaxResult getDivineCase(Integer type) {
		if(null == type) {
			return AjaxResult.error("请选择类型");
		}
		return appSystemService.getDivineCase(type);
	}
	
	/**
	 * 	获取使用须知
	 * @param type 1=如何使用塔罗 2=如何使用骰子 3=如何使用六爻 4=如何注册登录 5=如何实名认证 6=发布版本问题
	 * 7= 用户协议 8=隐私协议 9=关于我们 10=VIP权益 11=单项问题预约须知 12=活动预约须知
	 * @return
	 */
	@GetMapping(value = "/getExplian")
	public AjaxResult getExplain(Integer type) {
		if(null == type) {
			return AjaxResult.error("请选择类型");
		}
		return appSystemService.getExplain(type);
	}
	
	/**
	 * 	app版本信息
	 * @return
	 */
	@GetMapping(value = "/appVersion")
	public AjaxResult appVersion(HttpServletRequest request) {
		return appSystemService.appVersion(request);
	}
	
	@Autowired
	private RedisUtil redisUtil;
	
	/**
	 * 	设置审核状态
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/getExamineStatus")
	public AjaxResult getExamineStatus(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int isOppo = 1;
		Object object = redisUtil.get("oppoExamineStatus");
		if(null != object) {
			isOppo = Integer.valueOf(object.toString());
		}
		map.put("oppo", isOppo);
		return AjaxResult.success(map);
	}
	
	@Autowired
	private TaskAsync taskAsync;
	
	@PostMapping(value = "/pushChatMsg")
	public AjaxResult pushChatMsg(@RequestBody AppSystemMsgDTO msg) {
		if(null == msg || null == msg.getUserId() || StringUtils.isEmpty(msg.getContent())) {
			return AjaxResult.error();
		}
		taskAsync.pushChatMsg(msg.getContent(), msg.getUserId());
		return AjaxResult.success();
	}
	
	/**
	 * 	环信IM回调- 收到回调 推送个推消息
	 * @param retStr
	 * @param httpServletRequest
	 * @return
	 */
	@RequestMapping(value = "/testPushNotify", method = { RequestMethod.POST, RequestMethod.GET })
	public AjaxResult testPushNotify(@RequestBody String retStr,HttpServletRequest httpServletRequest) {
		System.out.println("回调成功");
		System.out.println(retStr);
		if(StringUtils.isNotEmpty(retStr)) {
			Long userId = 0L;
			String content = "";
			JSONObject retObject = JSONObject.parseObject(retStr);
			JSONObject payload = retObject.getJSONObject("payload");
			if(null != payload) {
				JSONObject ext = payload.getJSONObject("ext");
				if(null != ext) {
					userId = ext.getLong("userId_your");
				}
				JSONArray bodies = payload.getJSONArray("bodies");
				if(null != bodies) {
					JSONObject msg = bodies.getJSONObject(0);
					if(null != msg) {
						content = msg.getString("msg");
					}
				}
			}
			if(userId > 0 && StringUtils.isNotEmpty(content)) {
				taskAsync.pushChatMsg(content, userId);
				// 设置消息已读
				appSystemService.setReadMsg(userId);
			}
		}
		return AjaxResult.success();
	}
	
	/**
	 * 	我的账号管理
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/getAccountManage")
	public AjaxResult getAccountManage() {
		return appSystemService.getAccountManage();
	}
	
	/**
	 * 	添加关联账号
	 * @return
	 */
	@PostMapping(value = "/addAccountManage")
	public AjaxResult addAccountManage(@RequestBody AppRegister appRegister) {
		if(null == appRegister || StringUtils.isEmpty(appRegister.getMobile())) {
			return AjaxResult.error("请输入手机号码");
		}
		if(StringUtils.isEmpty(appRegister.getMobileCode())) {
			return AjaxResult.error("请输入验证码");
		}
		return appSystemService.addAccountManage(appRegister.getMobile(),appRegister.getMobileCode());
	}
	
	/**
	 * 	删除关联账号
	 * @param manage
	 * @return
	 */
	@PostMapping(value = "/delAccountManage")
	public AjaxResult delAccountManage(@RequestBody AppAccountManageVO manage) {
		if(null == manage || null == manage.getId()) {
			return AjaxResult.error("请选择账号");
		}
		return appSystemService.delAccountManage(manage.getId());
	}
	
	/**
	 * 	消息已读通知
	 * @return
	 */
	@GetMapping(value = "/msgReadNotice")
	public AjaxResult msgReadNotice() {
		return appSystemService.msgReadNotice();
	}
	
	/**
	 * 	是否有未读消息
	 * @return
	 */
	@GetMapping(value = "/isUnreadMsg")
	public AjaxResult isUnreadMsg() {
		return appSystemService.isUnreadMsg();
	}
	
	/**
	 * 	清除未读消息
	 * @return
	 */
	@GetMapping(value = "/cleanUnreadMsg")
	public AjaxResult cleanUnreadMsg() {
		return appSystemService.cleanUnreadMsg();
	}
	
	
	@GetMapping(value = "/qryAliAK")
	public AjaxResult qryAliAK() {
		Map<String,String> retMap = new HashMap<String, String>();
		retMap.put("AccessKeyID", "LTAI5t8vauBi4WQ8fZUq4MsT");
		retMap.put("AccessKeySecret", "D2x0wcd5I5Ms5Z36imPSVS2hQ6jK37");
		return AjaxResult.success(retMap);
	}
	
	@GetMapping(value = "/isShowGift")
	public AjaxResult isShowGift() {
		return AjaxResult.success("成功",0);
	}
	
	
	@GetMapping(value = "/isWithdraw")
	public AjaxResult isWithdraw() {
		return AjaxResult.success("成功",0);
	}
	
	/**
	 * 	获取客服信息
	 * @return
	 */
	@GetMapping(value = "/getCustomerInfo")
	public AjaxResult getCustomerInfo() {
		return appSystemService.getCustomerInfo();
	}
	
	/**
	 * 	是否开启微信支付
	 * @return
	 */
	@GetMapping(value = "/isWechatPay")
	public AjaxResult isWechatPay() {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("isWechatPay", 0); // 是否开启微信支付
		map.put("isAliPay", 1); // 是否开启支付宝支付
		return AjaxResult.success(map);
	}
	
}
